<template>
  <n-card :header-style="{ padding: '10px', background: '#F1F5FF', marginBottom: '10px' }">
    <template #header> 媒体账户</template>
    <x-form ref="formRef" v-model:model="adv" :rules="rules" label-placement="top" label-width="140">
      <n-form-item label="选择账户" path="accounts" v-if="accountsAuth.operation" ref="elementRef">
        <div class="flex items-center" @click="handleShowModal">
          <text class="link-color cursor-pointer">选择媒体账户</text>
          <n-icon size="20" class="link-color">
            <UsergroupAddOutlined></UsergroupAddOutlined>
          </n-icon>
        </div>
      </n-form-item>
    </x-form>
    <div v-for="mdm in mdmSortAccounts" :key="mdm.id" class="mb-10 mdm-card">
      <div class="mb-10 title" v-if="mdm.name">{{ mdm.name }}</div>
      <div>
        <n-tag size="large" :bordered="false" v-for="(item, i) in mdm.accounts" class="mr-10" :closable="!item.disabled"
          @close="handleRemove(item.id)">{{ item.accountCode }}</n-tag>

      </div>
    </div>
  </n-card>

  <!-- <n-button @click="selectAccount">选择账户测试入口</n-button> -->

  <n-modal v-model:show="modal.show" preset="card" :bordered="false" :style="{ width: '820px' }" :mask-closable="false">
    <template #header>
      <div>
        {{ modal.title }}
        <span class="warn-color ml-5 font-12">最多选择{{ modal.maxSelect }}个账户</span>
      </div>
    </template>

    <div class="flex items-center account-search">
      <div class="flex flex-1">
        <div class="label text-right">账户主体</div>
        <n-select placeholder="请选择账户主体" :key="modalSearchForm.mdmName || 0" v-model:value="modalSearchForm.mdmName" filterable clearable
          :options="modal.mdmOptional"></n-select>
      </div>
      <div class="flex flex-1 ml-20">
        <div class="label text-right">账户ID</div>
        <n-select placeholder="请选择账户ID" :key="modalSearchForm.accountCode || 0" filterable v-model:value="modalSearchForm.accountCode" clearable
          :options="modal.accountOptional"></n-select>
      </div>
      <div class="ml-20">
        <x-button type="primary" @click="searchAccout">搜索</x-button>
        <x-button type="default" @click="resetAccount">重置</x-button>
      </div>
    </div>
    <div class="mt-10">
      已选<span>{{ modal.checkRows.length }}</span>个账户
      <span type="text" class="ml-10 link-color cursor-pointer" @click="emptySelect">清空已选</span>
    </div>
    <div>

      <x-data-table v-model:immediate="modal.immediate" @update:checked-row-keys="handleCheck" ref="tableRef"
        :checked-row-keys="modal.checkRows" :params="modal.params" :columns="modal.columns"
        :row-key="(row) => row.accountCode" :is-reload="false" row-class-name="text-sm" max-height="400" />

    </div>

    <template #footer>
      <div class="text-right">
        <n-button type="primary" @click="confirmSelect">确定</n-button>
      </div>

    </template>

  </n-modal>
</template>

<script setup lang="ts">
import { computed, reactive, defineExpose, ref, nextTick } from 'vue';
import { useStore } from '@/store';
import { FormItemRule, NCard, NModal, NButton, NFormItem, NSelect, NTag, NScrollbar, NText, NIcon } from 'naive-ui';
import { XForm, XButton, XDataTable } from '@/components';
import { mediaAccountList } from '@/api/system';
import { useMessage } from 'naive-ui';
import { getMdmNameList } from '@/api/intelligent';
import { getAccountOwnerList } from '@/api/account';

import { UsergroupAddOutlined } from '@vicons/antd';
import Account from '@/store/modules/adv/account';
// import { Acc}
const message = useMessage()
const store = useStore();
const adv = computed(() => store.state.adv);
const elementRef = ref();
const emit = defineEmits(['update', 'remove'])

defineProps({
  index: {
    type: Number
  }
})

const accountsAuth = computed(() => store.state.adv.accountsAuth)

const rules = {
  accounts: {
    type: 'any',
    required: true,
    validator(rule: FormItemRule, value: any) {
      if (!value.length) {
        return new Error('请至少选择一个账户!')
      }
      return true
    },
    trigger: ['change'],
    message: '请至少选择一个账户!'
  }
}


const mdmSortAccounts = computed(() => {
  const mdms: any = [];
  adv.value.accounts.map((account: any) => {
    let mdm = mdms.find((mdm: any) => mdm.id === account.mdmName);
    if (!mdm) {
      mdm = {
        id: account.mdmName,
        accounts: [],
        name: account.mdmName
      }
      mdms.push(mdm)
    }
    mdm.accounts.push(account);
  })
  return mdms;
})


// https://yapi.madaomall.com/mock/207/adgroup/account/code/list

const modalSearchForm = reactive({
  accountCode: undefined,
  mdmName: undefined,
  accountType: 0,
  systemStatus: 'CUSTOMER_STATUS_NORMAL'
})
const modal = reactive<any>({
  show: false,
  title: '选择媒体账户',

  mdmOptional: [],
  accountOptional: [],
  immediate: false,
  checkRows: [],
  tempChecks: [],
  tableData: [],
  pagination: {},
  maxSelect: 10,
  columns: [
    {
      type: 'selection',
      title: '',
      width: '60'
    },
    {
      title: '账户ID',
      key: 'accountCode'
    }, {
      title: '账户名称',
      key: 'accountName'
    }],
  params: {
    fetch: mediaAccountList,
    data: {
      accountType: 0,
      systemStatus: 'CUSTOMER_STATUS_NORMAL'

    }
  }

});
function searchAccout() {

  modal.params.data = modalSearchForm;
  // console.log(modal.params.data)
  modal.immediate = true;
}

function resetAccount() {
  modalSearchForm.accountCode = undefined;
  modalSearchForm.mdmName = undefined;

  modal.params.data = {
    accountType: 0,
    systemStatus: 'CUSTOMER_STATUS_NORMAL'
  };
  modal.immediate = true;
}




async function getMdmSearchList() {
  const mdms = await getMdmNameList({});
  modal.mdmOptional = mdms.data.map(_ => {
    return {
      label: _,
      value: _
    }
  })
}


async function getAccountOwnerSearchList() {
  const res = await getAccountOwnerList({
    systemStatus: 'CUSTOMER_STATUS_NORMAL'
  });
  modal.accountOptional = res.data.map((_: any) => {
    return {
      label: _,
      value: _
    }
  })
}
// shaixuan
getMdmSearchList();
getAccountOwnerSearchList();

function handleRemove(id: number) {

  const idx = adv.value.accounts.findIndex((_: any) => _.id === id)
  adv.value.accounts.splice(idx, 1);
  emit('remove');
}

function handleShowModal() {

  modal.show = true;
  modal.immediate = true;
  modal.checkRows = adv.value.accounts.map(account => account.accountCode);
  modal.tempChecks = adv.value.accounts;


}
function emptySelect() {
  modal.checkRows = [];
  modal.tempChecks = [];
}
function handleCheck(rowKeys: any, rows: object[], { action }: any) {
  // console.log('change', action);
  if (modal.checkRows.length >= modal.maxSelect && action === 'check') {
    message.warning(`数量已达${modal.maxSelect}个上限，请取消账户后再选择`)
    return;
  }
  if (action == 'checkAll') {

  }
  modal.checkRows = rowKeys.slice(0, modal.maxSelect);
  modal.tempChecks = rows.slice(0, modal.maxSelect).map(row => {
    return new Account(row)
  })
}

function confirmSelect() {
  adv.value.accounts = [].concat([], modal.tempChecks);
  store.commit('adv/UPDATE_ACCOUNTS', modal.tempChecks);
  modal.show = false;
  emit('update');
}


const formRef = ref()

function validate() {
  return new Promise<void>((resolve, reject) => {
    formRef.value?.validate(async (errors: any) => {
      if (!errors) {
        try {
          resolve()
        } catch (e) {
          store.commit('adv/SCROLL_TO_ELEMENT', elementRef.value.$el)
          reject()
        }
      } else {

        store.commit('adv/SCROLL_TO_ELEMENT', elementRef.value.$el)
        reject()
      }
    })
  })
}

defineExpose({
  validate
})



//
</script>
<style lang="scss" scoped>
.account-search {
  .label {
    width: 90px;
    margin-right: 10px;
  }
}

.mdm-card {
  background-color: #f7f9fc;
  padding: 10px;
  border-radius: 4px;
}
</style>
